package com.example.controller;

import com.example.POJO.Account;
import com.example.POJO.Product;
import com.example.POJO.User;
import com.example.mapper.AccountMapper;
import com.example.mapper.UserMapper;
import com.example.service.AccountService;
import com.example.service.UserService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    AccountService accountService;
    @Autowired
    UserService userService;

    @PostMapping(value = "/getUserByPhone", consumes = "application/json;charset=UTF-8")
    public String getUserByPhone(@RequestBody HashMap<String, String> data) {
        try {
            System.out.println(data);
            String phone = data.get("phone");
            Integer id = accountService.getIdByPhone(phone);
            User user = userService.getUserById(id);
            Gson gson = new Gson();
            String res = gson.toJson(user);
            System.out.println(res);
            return res;

        } catch (Exception e) {
            // 处理异常，返回相应的错误响应
            System.out.println(e);
            return "";
        }
    }

    @PostMapping(value = "/getUserById", consumes = "application/json;charset=UTF-8")
    public String getUserById(@RequestBody HashMap<String, String> data) {
        try {
            String id = data.get("user_id");
            User user = userService.getUserById(Integer.valueOf(id));
            Gson gson = new Gson();
            String res = gson.toJson(user);
            System.out.println(res);
            return res;

        } catch (Exception e) {
            // 处理异常，返回相应的错误响应
            System.out.println(e);
            return "";
        }
    }

    @PostMapping(value = "/userAlter", consumes = "application/json;charset=UTF-8")
    public String updateUser(@RequestBody HashMap<String, String> data) {

        try {
            // 在这里，您可以访问从客户端发送的数据
            String id = data.get("id");
            String name = data.get("name");
            String sex = data.get("sex");
            String birth = data.get("birth");

            User user = new User();

            user.setId(Integer.valueOf(id));
            user.setName(name);
            user.setSex(sex);
            user.setBirth(birth);


            // 进行业务逻辑处理，存储到数据库等
            userService.updateUser(user);
            return "true";

        } catch (Exception e) {
            // 处理异常，返回相应的错误响应
            System.out.println(e);
            return "false";
        }
    }
}
